package com.example.pan.http

import android.util.Log
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import retrofit2.Invocation

class MultiInterceptor : Interceptor {

    companion object {
        const val PAN_URL = "https://pan.baidu.com/"
        const val ARIA2_URL = "http://127.0.0.1:6800/"
    }

    private val map: Map<String, (request: Request) -> Request> = mapOf(
        Pair(ARIA2_URL, object : (Request) -> Request() {
            override fun invoke(request: Request): Request {
                return request
            }
        }),
        Pair(PAN_URL, object : (Request) -> Request() {
            override fun invoke(request: Request): Request {
                val newBuilder = request.newBuilder()
                newBuilder.addHeader("User-Agent", "pan.baidu.com")
                return newBuilder.build()
            }
        })
    )

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val baseUrl =
            request.tag(Invocation::class.java)
                ?.method()?.declaringClass?.getAnnotation(BaseUrl::class.java)?.value
        var url = request.url
        var handler = map[getDefaultBaseUrl()]
        baseUrl?.apply {
            url = parseUrl(this, url)
            handler = map[this]
            if (handler == null) {
                Log.e("切换BaseUrl失败", this)
            }
        }
        val invoke = handler!!.invoke(request.newBuilder().url(url).build())
        return chain.proceed(invoke)
    }

    private fun getDefaultBaseUrl(): String = ARIA2_URL

    private fun parseUrl(baseUrl: String, url: HttpUrl): HttpUrl {
        val base = baseUrl.toHttpUrl()
        return url.newBuilder()
            .scheme(base.scheme)
            .host(base.host)
            .port(base.port)
            .build()
    }

}